<template>
	<view class="main-admin">
		<div class="form-box shadow" style="width: 100%;">
			<div class="input-group">
				<div style="font-weight: bold;">{{ jzname }}</div>
			</div>
			<div class="input-group">
				<label class="password-label">起始日期</label>
				<div class="kaoyb">
					<picker mode="date" :value="startDateValue" :start="startDate" :end="endDate"
						@change="bindStartDateChange">
						<view class="uni-input">{{ startDateValue }}</view>
					</picker>
				</div>
			</div>
			<div class="input-group">
				<label class="password-label">终止日期</label>
				<div class="kaoyb">
					<picker mode="date" :value="endDateValue" :start="startDate" :end="endDate"
						@change="bindEndDateChange">
						<view class="uni-input">{{ endDateValue }}</view>
					</picker>
				</div>
			</div>
			<div class="input-group">
				<label class="password-label">数据类型</label>
				<div class="kaoyb">
					<picker @change="bindPickerChange3" :value="index3" :range="array3">
						<view class="uni-input">{{ array3[index3] }} <text class="kuoyi">></text></view>
					</picker>
				</div>
			</div>
		</div>
		<view class="form-box shadow">
			<view class="form-group">
				<view style="font-size:30rpx;font-weight: bold;">数据下载链接<text v-if="time"
						class="text-gray text-s margin-left-s">({{ time }} 生成)</text></view>
				<button hover-class="button-hover" class="btn bg-admin text-white shadow" @click="copyUrl"
					:data-type="'copy'" :data-url="urll">复制</button>
			</view>
			<view class="form-group align-start" @click="copyUrl" :data-type="'copy'" :data-url="urll">
				<textarea maxlength="500" placeholder="数据文件尚未生成，点击下方按钮生成" placeholder-class="phc" v-model="urll"
					style="height:50rpx;"></textarea>
			</view>
			<block v-if="urll">
				<view class="form-group" style="padding: 15px;padding-right: 10px;">
					<view class="title-desc">
						<text user-select="true">※ <text class="text-black">链接使用说明</text>
							1. 复制以上链接地址，建议在电脑浏览器中打开链接下载数据文件
							2. 为保障信息安全，请勿外传数据链接
							3. 为了防止隐私数据泄露，请在下载后及时点击下方按钮删除
						</text>
					</view>
				</view>
			</block>
		</view>
		<button @click="bindExportTap" class="btn-admin margin-top"
			style="margin-top: 10px;">{{ urll ? '重新生成数据' : '生成数据' }}(Excel文件)</button>
		<button v-if="urll" @click="bindOpenTap" class="btn-admin bg-purple light">直接打开数据文件</button>
		<button v-if="urll" @click="bindDelTap" class="btn-admin margin-bottom-s bg-red light">删除数据文件</button>
		<view v-if="urll" style="margin-top: 15px;">
			<view class="title-desc text-red"><text
					class="icon-info margin-right-xs"></text>为了防止隐私数据泄露，请在下载上述文件后及时点击按钮删除</view>
		</view>
		<view v-show="state" class="overlay" @click="overlayClick">
			<view class="action-modal" @click.stop>
				<div>
					<div class="action-text">温馨提示</div>
					<div class="action-text2">数据文件生成成功(<text
							style="color: #8d8d8d;font-weight: bold;">{{ uconst }}</text>记录)，请点击「直接打开」按钮或者复制文件地址下载</div>
				</div>
				<view class="action-modal-content">
					<view class="action-item" @click="state = false">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import {
		url,
		getAppointmenCoent
	} from '@/request/api.js';
	import {
		getFormattedTime
	} from '@/request/wx.js';

	const urll = ref(null);
	const time = ref('');
	const state = ref(false);
	const uconst = ref(0);
	const jzname = ref('李小姐');
	const array3 = ref(['预约成功名单', '用户已取消名单', '系统取消名单', '所有名单']);
	const index3 = ref(0);

	const startDateValue = ref(getCurrentDate());
	const startDate = computed(() => getDate('start'));
	const endDateValue = ref(getCurrentDate());
	const endDate = computed(() => getDate('end'));

	const bindPickerChange3 = (e) => { //数据类型
		console.log('picker3发送选择改变，携带值为', e.detail.value);
		index3.value = e.detail.value;
	};
	let id;

	onLoad(async (options) => { // 页面加载时获取用户数据。这里的 options 参数包含了页面加载时传递的参数
		console.log('页面加载时获取用户数据', options);
		try {
			jzname.value = options.sname;
			id = options.id;
		} catch (error) {
			console.error("请求失败:", error);
		}
	});

	function getDate(type) { //日期
		const date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();

		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year + 2;
		}
		month = month > 9 ? month : '0' + month;
		day = day > 9 ? day : '0' + day;
		return `${year}-${month}-${day}`;
	}

	function getCurrentDate() { //日期
		const today = new Date();
		const year = today.getFullYear();
		const month = String(today.getMonth() + 1).padStart(2, '0');
		const day = String(today.getDate()).padStart(2, '0');
		return `${year}-${month}-${day}`;
	}

	function bindStartDateChange(event) { //起始日期
		const [year, month, day] = event.detail.value.split('-');
		startDateValue.value = event.detail.value;
	}

	function bindEndDateChange(event) { //终止日期
		const [year, month, day] = event.detail.value.split('-');
		endDateValue.value = event.detail.value;
	}

	function overlayClick() {
		console.log("阻止点击事件冒泡到覆盖层");
	}

	const copyUrl = () => { //复制链接的逻辑
		if (!urll.value) {
			uni.showToast({
				title: '链接为空'
			});
			return;
		}
		uni.setClipboardData({
			data: urll.value,
			success: () => {
				uni.showToast({
					title: '已复制到剪贴板'
				});
			},
			fail: () => {
				uni.showToast({
					title: '复制失败'
				});
			}
		});
	};

	const bindExportTap = async () => { //生成数据
		try {
			// console.log(startDateValue.value); //开始
			// console.log(endDateValue.value); //终止
			// console.log(array3.value[index3.value]); //数据类型
			let ccc = {
				id: id,
				start: startDateValue.value,
				end: endDateValue.value,
				type: array3.value[index3.value]
			}
			time.value = getFormattedTime();
			const res = await downloadFile(ccc);
			urll.value = res.tempFilePath;
			const userRes = await getAppointmenCoent(ccc);
			uconst.value = userRes.data.data;
			state.value = true;
		} catch (error) {
			console.error('处理文件时出错:', error);
		}
	};

	const bindOpenTap = () => { //直接打开数据文件
		if (urll.value) {
			uni.showToast({
				title: '打开文档'
			});
			wx.openDocument({
				filePath: urll.value,
				success(res) {
					console.log(res)
					console.log('打开文档成功');
				},
				fail(err) {
					console.error('打开文档失败:', err);
				}
			});
		} else {
			console.error('tempFilePath is undefined');
		}
	};

	const bindDelTap = () => { //删除数据文件
		urll.value = '';
		time.value = '';
	};

	async function downloadFile(ccc) { // 调用后端接口下载文件
		return new Promise((resolve, reject) => {
			let queryString = `id=${ccc.id}&start=${ccc.start}&end=${ccc.end}&type=${ccc.type}`;
			// console.log(queryString);
			wx.downloadFile({
				url: url() + `appointment/appointmengetid?` + queryString, // 替换为实际的URL
				success(res) {
					if (res.statusCode === 200) {
						resolve(res);
					} else {
						reject('下载失败，状态码：' + res.statusCode);
					}
				},
				fail(err) {
					reject('下载失败：' + err.errMsg);
				}
			});
		});
	}
</script>

<style scoped>
	.password-label::before {
		content: '*';
		color: red;
		font-weight: bold;
		vertical-align: middle;
		font-size: 1em;
	}

	.password-label {
		line-height: 1;
		display: inline-block;
		font-weight: bold;
	}

	.kuoyi {
		color: #8d8d8d;
		font-size: 20px;
	}

	.kaoyb {
		text-align: right;
	}

	.input-group {
		display: table;
		width: 90%;
		border-bottom: 1px solid #ebebeb;
		padding: 10px 15px;
	}

	.input-group:last-child {
		border-bottom: 0px solid;
	}

	.input-group .password-label,
	.input-group .kaoyb {
		display: table-cell;
		vertical-align: middle;
	}

	.input-group .kaoyb {
		width: 220px;
	}

	::v-deep textarea {
		line-height: 1.5;
	}

	.action-text2,
	.action-text {
		width: 100%;
		text-align: center;
		margin-bottom: 20px;
		font-size: 17px;
	}

	.action-text2 {
		color: #737373;
		line-height: 1.5;
	}

	.overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
		background-color: rgba(0, 0, 0, 0.1);
		z-index: 9999;
	}

	.action-modal {
		background-color: #fff;
		border-radius: 10px;
		width: 70%;
		max-width: 300px;
		box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
		position: absolute;
		bottom: 50%;
		left: 50%;
		transform: translate(-50%, 50%);
		z-index: 10000;
		padding: 25px;
	}

	.action-modal-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
		width: 100%;
	}

	.action-item {
		padding: 12px;
		margin-top: 10px;
		width: 55%;
		text-align: center;
		color: white;
		background-color: #00c469;
		border-radius: 6px;
		cursor: pointer;
	}

	.action-item:hover {
		background-color: #33d087;
	}

	.main-admin {
		padding: 15px 12px;
		background-color: #fff;
		border-radius: 8px;
	}

	.form-box {
		border-radius: 4px;
		margin-bottom: 20px;
	}

	.form-group {
		padding: 15px;
		padding-right: 10px;
		border-bottom: 1px solid #ebebeb;
	}

	.align-start {
		padding-top: 20px;
		padding-bottom: 20px;
	}

	.title-desc {
		color: #888;
		font-size: 15px;
	}

	.title {
		font-size: 16px;
		color: #333;
	}

	.text-gray {
		margin-left: 10px;
		color: #aaa;
		font-size: 13px;
	}

	.text-black {
		color: #000;
	}

	.text-red {
		color: #f56c6c;
	}

	.icon-info {
		color: #f56c6c;
	}

	.btn {
		width: 196px;
		border-radius: 6px;
		border: none;
		outline: none;
		cursor: pointer;
		font-size: 16px;
		font-weight: 500;
		letter-spacing: 0.5px;
		text-transform: uppercase;
		transition: all 0.3s ease;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		align-items: center;
		justify-content: center;
		margin-top: 12px;
	}

	.btn:hover {
		opacity: 0.9;
		transform: translateY(-2px);
	}

	.btn:active {
		transform: translateY(2px);
	}

	.bg-admin {
		background-color: #409eff;
		box-shadow: 0 4px 6px rgba(64, 158, 255, 0.3);
		color: #ffffff;
	}

	.bg-purple {
		background-color: #7c4dff;
		box-shadow: 0 4px 6px rgba(124, 77, 255, 0.3);
		color: #ffffff;
		margin-top: 5px;
	}

	.bg-red {
		background-color: #f56c6c;
		box-shadow: 0 4px 6px rgba(245, 108, 108, 0.3);
		color: #ffffff;
		margin-top: 5px;
	}

	.light {
		color: #fff;
	}

	.shadow {
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
	}

	.button-hover {
		background-color: #66b1ff;
	}

	.phc::placeholder {
		color: #aaa;
	}
</style>